var boardTable;
var searchForm;

function initTable(oneClientData, oneProjectData, subMenuItemCode) {
	var titleText = 
		oneClientData['clientName'] + ' / '	+ 
		oneProjectData['projectName'] + ' / ' + 
		subMenuItemCode;
	
	boardLayout.setText(titleText);
	boardLayout.attachHTMLString(
			'<div id="gridDiv"></div>' +
			'<div id="pagingDiv"></div>' +
			'<div id="searchDiv"></div>'
	);
	
	boardTable = new dhtmlXGridObject('gridDiv');
	boardTable.setImagesPath(IMAGE_PATH + '/dhxgrid_web/');
	boardTable.setHeader(['번호', '제목', '작성자', '작성일','조회']);
	boardTable.setInitWidths('80, 300, 110, 110, 45');
	boardTable.setColAlign('left, left, left, left','left');
	boardTable.setColSorting('int, str, str, str','int');
	boardTable.enableAutoWidth(true);
	boardTable.enableAutoHeight(true);
	boardTable.enableRowsHover(true, 'grid_hover');
	boardTable.enablePaging(true, SHOW_DATA_PER_PAGE, 10, 'pagingDiv', true);
	//boardTable.setPagingSkin('default');
	boardTable.init();
	boardTable.setPagingTemplates('[prevpages:< 이전:] [currentpages: ] [nextpages:다음 >:]', '');
	
	boardTable.attachEvent('onRowSelect', function(id, ind) {
		var seq = boardTable.cellById(id, 0);
		
		if ( seq.getValue() != '' ) {
			initReadContent(oneClientData, oneProjectData, subMenuItemCode, seq.getValue());
		}
	});
	boardTable.attachEvent('onBeforePageChanged', function() {
    	if ( !this.getRowsNum() ) {
    		return false;
    	}
    	
    	return true;
	});
	boardTable.attachEvent('onPageChanged', function(curPage, startPos, endPos) {
//		console.log(curPage + '/' + startPos + '/' + endPos);
		getBoardList(startPos, endPos);
	});
	
	getBoardList(0, SHOW_DATA_PER_PAGE);
	initSearchForm(oneClientData, oneProjectData, subMenuItemCode);
}

function getBoardList(startPos, endPos) {
	var boardInfo = $.ajax({
		url : '/bwf/board/list/' + startPos + '/' + endPos
		,type : 'GET'
	});
	boardInfo.done(function(params) {
		boardTable.clearAll();
		var totalCount 	= params[0];
		var boardList	= params[1];
		
		if ( totalCount != null && boardList != null ) {
			var buffer = new StringBuffer();
			
			buffer.append("<rows total_count='" + totalCount + "' pos='" + startPos + "'>\r\n");
			
			for ( var i = 0; i < boardList.length; i++ ) {
				var data = boardList[i];
				var title;
				if ( 0 < data['commentCnt'] ) {
					title = '<![CDATA['+data['title']+'<font color="red"; >['+ data['commentCnt']+']</font>]]>';
				}
				else {//<![CDATA[<font color="red">7.99</font>]]>
					title = data['title'];
				}
				buffer.append("<row id='" + (i + 1) + "'>\r\n");
				buffer.append("<cell>" + data['num'] + "</cell>\r\n");
				buffer.append("<cell>" + title + "</cell>\r\n");
				buffer.append("<cell>" + data['writer'] + "</cell>\r\n");
				buffer.append("<cell>" + data['reg_date'] + "</cell>\r\n");
				buffer.append("<cell>" + data['readcount'] + "</cell>\r\n");
				buffer.append("</row>\r\n");
			}
			
			buffer.append("</rows>");
			
			boardTable.parse(buffer.toString());
		}
		else { 
			boardTable.addRow(1, ['', '등록된 게시물이 없습니다.']);
		}
	});
	boardInfo.fail(function(jqXHR, textStatus) {
		alert('Request failed!');
	});
}

function initSearchForm(oneClientData, oneProjectData, subMenuItemCode) {
	var searchFormData = [
	                      {type : 'settings', position : 'label-left'}
	                      ,{type : 'block', blockOffset : 80
	                    	  ,list : [
	                    	           {type : 'combo', name : 'combo_SearchDate', readonly : true, filtering : true
	                    	        	   ,inputWidth : 100
	                    	        	   ,options : [
	                    	        	              {text: '전체기간', value: 'ALL', selected: true}
	                    	        	              ,{text: '1일', value: '1DAY'}
	                    	        	              ,{text: '7일', value: '7DAY'}
	                    	        	              ,{text: '1달', value: '1MON'}
	                    	        	              ,{text: '3달', value: '3MON'}
	                    	        	              ]
	                    	           }
	                    	           ,{type : 'newcolumn'}
	                    	           ,{type : 'combo', name : 'combo_SearchKeyword', readonly : true, filtering : true
	                    	        	   ,inputWidth : 100
	                    	        	   ,options : [
	                    	        	              {text: '제목', value: 'TITLE', selected: true}
	                    	        	              ,{text: '내용', value: 'CONTENT'}
	                    	        	              ,{text: '작성자', value: 'WRITER'}
	                    	        	              ]
	                    	           }
	                    	           ,{type : 'newcolumn'}
	                    	           ,{type : 'input', name : 'input_search', width : 150}
	                    	           ,{type : 'newcolumn'}
	                    	           ,{type : 'button', name : 'button_search', value : '검색', offsetLeft : 5}
	                    	           ,{type : 'newcolumn'}
	                    	           ,{type : 'button', name : 'button_write', value : '글쓰기'}
	                    	           ]
	                      }];
	
	searchForm = new dhtmlXForm('searchDiv', searchFormData);
	
	//Button Event
	searchForm.attachEvent('onButtonClick', function(name, command) {
		if ( name == 'button_search' ) {
			checkSearch();
		}
		else if ( name == 'button_write' ) {
			initWrite(oneClientData, oneProjectData, subMenuItemCode);
		}
	});
	//Key Event
	searchForm.attachEvent('onKeyDown',function(inp, ev, name, value) {
		if ( name == 'input_search' ) {
			if( ev.keyCode == 13 ){
				checkSearch();
			}
		}
	});
}

function checkSearch() {
	var search     = searchForm.getItemValue('input_search');
	var searchKey  = searchForm.getItemValue('combo_SearchKeyword');
	var dateOption = searchForm.getItemValue('combo_SearchDate');
	
	if ( search != '' ) {
		getSearchList(searchKey, search, dateOption);	
	}
	else {
		dhtmlx.alert({
			title : 'search Error'
			,type : 'alert-error'
			,text : '검색어를 입력해주세요.'
		});
	}
}

function getSearchList(searchKey, search, dateOption) {
	var boardInfo = $.ajax({
		url : '/bwf/board/searchList/' + searchKey + '/' + search + '/' + dateOption
		, type : 'GET'
		, dataType : 'json'
	});
	boardInfo.done(function(boardList) {
		boardTable.clearAll();
		if ( boardList.length > 0 ) {
			for ( var i = 0; i < boardList.length; i++ ) {
				data = boardList[i];
				boardTable.addRow(
						i + 1
						,[data['num'], data['title'], data['writer'], data['reg_date'], data['readcount']]);
			}
		}
		else {
			boardTable.addRow(1, [' ','등록된 게시물이 없습니다.']);
			boardTable.setRowId(0, 'row1');
			boardTable.setRowTextBold('row1');
			boardTable.setRowTextStyle('row1', 'background-color : lightgray; font-family : arial;');
			boardTable.setRowspan('row1', 0, 4);
		}
	});
	boardInfo.fail(function(jqXHR, textStatus) {
		alert('Request failed!');
	});
}
